package com.vankimgps.database;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import com.vankimgps.models.UserInfos;

import android.R.bool;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DatabaseHelper extends SQLiteOpenHelper{

	private static String DB_PATH = "/data/data/com.vankimgps.activity/databases/";
	private static String DB_NAME = "vankimGPS.sqlite";
	private SQLiteDatabase myDataBase; 
	private final Context myContext;
	private static final int DATABASE_VERSION = 1;

	public DatabaseHelper(Context context) {
		super(context, DB_NAME, null, DATABASE_VERSION);
		this.myContext = context;
	}
	
	public void createDataBase() throws IOException{
        boolean dbExist = checkDataBase();

        if(dbExist){
            //do nothing - database already exist
            this.getWritableDatabase();
            this.close();
        }else{
            //By calling this method and empty database will be created into the default system path
               //of your application so we are gonna be able to overwrite that database with our database.
            this.getReadableDatabase();
            this.close();
            try {
                copyDataBase();
            } catch (IOException e) {
            //throw new Error("Error copying database message");
            }
        }
    }

	private boolean checkDataBase(){
		SQLiteDatabase checkDB = null;
        try{
            String myPath = DB_PATH + DB_NAME;
            checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
        }catch(SQLiteException e){
            //database does't exist yet.
        }

        if(checkDB != null){
            checkDB.close();
        }

        return checkDB != null ? true : false;
    }

	private void copyDataBase() throws IOException{
        //Open your local db as the input stream
        InputStream myInput = myContext.getAssets().open(DB_NAME);

        // Path to the just created empty db
        String outFileName = DB_PATH + DB_NAME;
        
        //Open the empty db as the output stream
        OutputStream myOutput = new FileOutputStream(outFileName);

        //transfer bytes from the inputfile to the outputfile
        byte[] buffer = new byte[1024];
        int length;
        while ((length = myInput.read(buffer))>0){
            myOutput.write(buffer, 0, length);
        }

        //Close the streams
        myOutput.flush();
        myOutput.close();
        myInput.close();
    }

	public void openDataBase() throws SQLException{
        //Open the database
		if ((myDataBase == null) || (myDataBase.isOpen() == false) ){
			String myPath = DB_PATH + DB_NAME;
			myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
			Log.i("VANKIM","VANKIM: Database was opened");
		}
    }

    @Override
    public synchronized void close() {
    	if(myDataBase != null)
    		myDataBase.close();
    	super.close(); 
    }

    @Override
    public void onCreate(SQLiteDatabase db) {


    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {


    }
    
    public List<String> getAllConfigID() {
    	openDataBase();
        List<String> comments = new ArrayList<String>();

        String select = "Select ValueInt from Configs Where ConfigID='USERNAME'";
        
        Cursor cursor = myDataBase.rawQuery(select, null);

        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
        	comments.add(cursor.getString(0));
        	Log.i("VANKIM","VANKIM: data = " + cursor.getString(0));
        	cursor.moveToNext();
        }
        // Make sure to close the cursor
        cursor.close();
        return comments;
      }
    
    public void updateUsername(){
    	openDataBase();
    	
       String select = "Select valueInt from Configs Where ConfigID = 'USERNAME'";
        
        Cursor cursor = myDataBase.rawQuery(select, null);

        int i = 0;
        
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
        	i = cursor.getInt(0);
        	cursor.moveToNext();
        }
        // Make sure to close the cursor
        cursor.close();
        
        i++;
        
        ContentValues content = new ContentValues();
        content.put("ValueInt",i);
        
        try{
        	myDataBase.update("Configs", content, "ConfigID = 'USERNAME'", null);
        }catch(SQLException e){
        	Log.i("VANKIM","Error: " + e.toString());
        }
    }
    
    public void setUserInfo(UserInfos userInfo){
    	openDataBase();
    	
    	String SQL = "Update Users " +
    				 "Set RecID = '" + userInfo.getRecID() + "'," +
    						" Token = '" + userInfo.getToken() + "'," + 
    						" NickName = '" + userInfo.getNickName() + "'," + 
    						" Contact = '" + userInfo.getContact() + "'," + 
    						" Address = '" + userInfo.getAddress()  + "'";
//        ContentValues content = new ContentValues();
//        content.put("RecID",userInfo.getRecID());
//        content.put("Token", userInfo.getToken());
//        content.put("NickName", userInfo.getNickName());
//        content.put("Contact", userInfo.getContact());
//        content.put("Address", userInfo.getAddress());
//        int count = 0;
//        try{
//        	count = myDataBase.update("Users", content, "RowID = 1", null);
//        }catch(SQLException e){
//        	Log.i("VANKIM","VANKIM e: " + e.toString());
//        }
    	myDataBase.execSQL(SQL);
//    	Log.i("VANKIM","VANKIM: SQL = " + SQL);
    }
    
    public UserInfos getUserInfo(){
    	UserInfos userInfo = new UserInfos();

       String select = "Select RecID,Token,NickName,Contact,Address from Users";
        
        Cursor cursor = myDataBase.rawQuery(select, null);
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
        	userInfo.setRecID(cursor.getString(0));
        	userInfo.setToken(cursor.getString(1));
        	userInfo.setNickName(cursor.getString(2));
        	userInfo.setContact(cursor.getString(3));
        	userInfo.setAddres(cursor.getString(4));
        	cursor.moveToNext();
        }

        // Make sure to close the cursor
        cursor.close();

    	return userInfo;
    }
    
    public String getUserName(){
    	openDataBase();
    	
        String select = "Select valueText from Configs Where ConfigID = 'USERNAME'";
         
        Cursor cursor = myDataBase.rawQuery(select, null);
 
        String UserName = "";
         
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
         	UserName = cursor.getString(0);
         	cursor.moveToNext();
        }
         // Make sure to close the cursor
        cursor.close();
    	return UserName;
    }
    
    public void setUserName(String UserName){
    	openDataBase();
    	
         ContentValues content = new ContentValues();
         content.put("ValueText",UserName);
         
         try{
         	myDataBase.update("Configs", content, "ConfigID = 'USERNAME'", null);
         }catch(SQLException e){
         	Log.i("VANKIM","Error: " + e.toString());
         }    	
    }
    
    public String getPassword(){
    	openDataBase();
    	
        String select = "Select valueText from Configs Where ConfigID = 'PASSWORD'";
         
        Cursor cursor = myDataBase.rawQuery(select, null);
 
        String value = "";
         
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
        	value = cursor.getString(0);
         	cursor.moveToNext();
        }
         // Make sure to close the cursor
        cursor.close();
    	return value;
    }

    public void setPassword(String value){
    	openDataBase();
    	
         ContentValues content = new ContentValues();
         content.put("ValueText",value);
         
         try{
         	myDataBase.update("Configs", content, "ConfigID = 'PASSWORD'", null);
         }catch(SQLException e){
         	Log.i("VANKIM","Error: " + e.toString());
         }    	
    }
    
    public Boolean getLogin(){
    	openDataBase();
    	
        String select = "Select valueBoolean from Configs Where ConfigID = 'LOGIN'";
         
        Cursor cursor = myDataBase.rawQuery(select, null);
 
        Boolean value = false;
         
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
        	value = (cursor.getInt(0) == 1);
         	cursor.moveToNext();
        }
         // Make sure to close the cursor
        cursor.close();
    	return value;
    }

    public void setLogin(Boolean value){
    	openDataBase();
    	
         ContentValues content = new ContentValues();
         content.put("ValueBoolean",(value == true));
         
         try{
         	myDataBase.update("Configs", content, "ConfigID = 'LOGIN'", null);
         }catch(SQLException e){
         	Log.i("VANKIM","Error: " + e.toString());
         }    	
    }
    
    public String getToken(){
    	openDataBase();
    	
        String select = "Select Token from Users";
         
        Cursor cursor = myDataBase.rawQuery(select, null);
 
        String value = "";
         
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
        	value = cursor.getString(0);
         	cursor.moveToNext();
        }
         // Make sure to close the cursor
        cursor.close();
    	return value;
    }
    
    public String getUserID(){
    	openDataBase();
    	
        String select = "Select RecID from Users";
         
        Cursor cursor = myDataBase.rawQuery(select, null);
 
        String value = "";
         
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
        	value = cursor.getString(0);
         	cursor.moveToNext();
        }
         // Make sure to close the cursor
        cursor.close();
    	return value;
    }
}